<?php
/**
 * Created by PhpStorm.
 * User: John
 * Date: 16-12-30
 * Time: 上午11:55
 */
namespace app\backend\controller;

use Business\Power\BackendPower;
use think\Controller;
use app\backend\model\Contract;
use app\backend\model\Business;
use think\Exception;
use app\backend\model\Building;

class ContractController extends Controller
{
    private $_memberId = null;
    private $_dtype    = null;
    public function __construct()
    {
        $this->_memberId = $this->isLogin();
        $this->_dtype    = session('dtype');
    }

    /**
     * 获取我的合同
     * @date   2017-01-18
     * @author wuhao
     *
     * @param int  $page  页数
     * @return
     */
    public function index()
    {
        $page     = I('page', 1, 'intval');
        $pageSize = I('page_size', 10, 'intval');
        $data     = [];

        try {
            if (!is_numeric($page) || $page<=0) {
                throw new Exception("参数错误!", 400);
            }
            $powerCheck = new BackendPower();
            if ($powerCheck->checkPower($this->_dtype, 'leaseList')) {
                $this->apiReturn(201, [], '无权操作');
            }
            $contractModel = new Contract();
            $res           = $contractModel->getContract($this->_memberId, $this->_dtype, $page, $pageSize);
            if (!$res) {
                throw new Exception("暂无数据！", 201);
            } else {
                $sum = $contractModel->countContract($this->_memberId, $this->_dtype);
                $total = ceil($sum / $pageSize);

                $data = [
                    'list'         => $res,
                    'current_page' => $page,
                    'total'        => $total
                ];
                $msg  = '查询成功';
                $code = 200;
            }
        } catch (Exception $e) {
            $msg  = $e->getMessage();
            $code = $e->getCode();
        }

        $this->apiReturn($code, $data, $msg);
    }

    /**
     * 查看单个合同信息
     * @date   2017-01-18
     * @author wuhao
     *
     * @param  int  $id  合同ID
     *
     * @return
     */
    public function contractDetail()
    {
        $contractId = I('id', '', 'intval');
        $data = '';

        try {
            if (empty($contractId) || !is_numeric($contractId) || $contractId <= 0) {
                throw new Exception('参数错误！', 400);
            }
            $contractModel = new Contract();
            $res = $contractModel->getContractDetail($this->_dtype, $contractId);
            if (!$res) {
                throw new Exception('没有数据！', 201);
            } else {
                $data = $res;
                $msg  = '查询成功';
                $code = 200;
            }
        } catch (Exception $e) {
            $msg  = $e->getMessage();
            $code = $e->getCode();
        }

        $this->apiReturn($code, $data, $msg);
    }
}
